import Taro from "@tarojs/taro";
import { TOKEN_KEY } from "../app.config";

export const hasLogin = () => {
    return Taro.getStorageSync(TOKEN_KEY).length > 0;
};

function tabBarClick(value) {
    switch (value) {
        case 0:
            Taro.redirectTo({
                url: `/pages/index/index`
            });
            break;
        case 1:
            Taro.redirectTo({
                url: `/pages/find/find`
            });
            break;
        case 2:
            break;
        case 3:
            Taro.redirectTo({
                url: `/pages/message/message`
            });
            break;
        case 4:
            Taro.redirectTo({
                url: `/pages/my/my`
            });
            break;
        default:
            break;
    }
}

/*获取当前页url*/
function getCurrentPageUrl() {
    let pages = Taro.getCurrentPages();
    let currentPage = pages[pages.length - 1];
    return currentPage.route;
}

function formatNumber(n) {
    n = n.toString();
    return n[1] ? n : "0" + n;
}

function FormatTime(date) {
    const year = date.getFullYear();
    const month = date.getMonth() + 1;
    const day = date.getDate();
    const hour = date.getHours();
    const minute = date.getMinutes();
    const second = date.getSeconds();

    return (
        [year, month, day].map(formatNumber).join("/") +
        " " +
        [hour, minute, second].map(formatNumber).join(":")
    );
}

function logError(name, action, info?) {
    if (!info) {
        info = 'empty';
    }
    let device;
    try {
        let deviceInfo = Taro.getSystemInfoSync();
        device = JSON.stringify(deviceInfo);
    } catch (e) {
        console.error('not support getSystemInfoSync api', e.message);
    }
    let time = FormatTime(new Date());
    console.error(time, name, action, info, device);
    // if (typeof action !== 'object') {
    // fundebug.notify(name, action, info)
    // }
    // fundebug.notifyError(info, { name, action, device, time })
    if (typeof info === 'object') {
        info = JSON.stringify(info);
    }
}

export const CommonFunction = {
    tabBarClick: (value) => tabBarClick(value),
    getCurrentPageUrl: () => getCurrentPageUrl(),
    FormatTime: (date) => FormatTime(date),
    logError: (name, action, info?) => logError(name, action, info)
};
